package com.smt.modules.bus.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.smt.common.exception.RRException;
import com.smt.common.utils.TimeUtil;
import com.smt.modules.bus.vo.StreamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.utils.PageUtils;
import com.smt.common.utils.Query;

import com.smt.modules.bus.dao.StreamDao;
import com.smt.modules.bus.entity.StreamEntity;
import com.smt.modules.bus.service.StreamService;


@Service("streamService")
@Slf4j
public class StreamServiceImpl extends ServiceImpl<StreamDao, StreamEntity> implements StreamService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<StreamEntity> page = this.selectPage(
                new Query<StreamEntity>(params).getPage(),
                new EntityWrapper<StreamEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Async
    public Map<String,String> getVerifyCode(String signName, String smsCode, String extend, String param, String mobileNumber) {
        log.info("获取验证码入参:signName:{},code:{},extend:{},param:{},phoneNums:{}",signName,smsCode,extend,param,mobileNumber);
        log.info("马上调阿里云短信服务时当前线程：{}",Thread.currentThread().getId());
        //调阿里云短信服务
        String code = "";
        boolean flag = true;
        try {
            code = sendSms(signName,smsCode,null,param,mobileNumber);
            log.info("发送短信返回code:{}",code);
        } catch (ClientException e) {
            log.info("发送短信异常e[{}]",e);
            flag = false;
        }
        if (code.equals("OK") && flag) {
            StreamEntity smsStreamDo = new StreamEntity(signName,smsCode,mobileNumber,param,new Date(),1);
            super.insert(smsStreamDo);
            return JSONObject.parseObject(param,Map.class);
        }else if (!flag) {
            StreamEntity smsStreamDo = new StreamEntity(signName,smsCode,mobileNumber,param,new Date(),0);
            super.insert(smsStreamDo);
            throw new RRException("获取失败，请检查手机号是否正确");
        }else if (code.equals("isv.BUSINESS_LIMIT_CONTROL")) {
            //业务限流1分钟1次，1小时5次，1天10次
            int count;
            String msg = "";
            count = this.countByMobileNumber(mobileNumber, TimeUtil.getCurrentBeginDate(),TimeUtil.getCurrentEndDate());
            if (count == 10) {
                msg = "今日获取验证码次数已到上限，请24小时后重试。";
            }else if (count < 10 && count >= 5) {
                count =  this.countByMobileNumber(mobileNumber,TimeUtil.addDate(new Date(),0,-60),new Date());
                if (count == 5) {
                    msg = "操作过于频繁，请稍后尝试。";
                }
            }else {
                msg = "获取验证码过于频繁，请60秒后重试。";
            }
            StreamEntity smsStreamDo = new StreamEntity(signName,smsCode,mobileNumber,param,new Date(),0);
            super.insert(smsStreamDo);
            throw new RRException(msg);
        }else {
            throw new RRException("获取失败，请检查手机号是否正确");
        }
    }

    /**
     * @description 发送短信,需要引入阿里云两个jar包
     * @author
     * @date 2018/7/17 下午2:30
     */
    private  String sendSms(String signName,String code,String extend,String param,String phoneNums) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK
        final String accessKeyId = "LTAIZ23GxVW9LOhO";//你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "27dDEYAEuPXEwEFmQsXV5fzEt47ODd";//你的accessKeySecret，参考本文档步骤2

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNums);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(code);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(param);
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(extend);

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse == null?null:sendSmsResponse.getCode();
    }

    @Override
    public Integer countByMobileNumber(String mobileNumber, Date startDate, Date endDate) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("phone",mobileNumber);
        wrapper.ge("create_time",startDate);
        wrapper.le("create_time",endDate);
        return baseMapper.selectCount(wrapper);
    }

    @Override
    public StreamVo selectOneByMobileNumber(String mobileNumber) {
        StreamEntity smsStreamDo = super.selectOne(new EntityWrapper().eq("phone",mobileNumber).orderBy("create_time",false));
        log.info("根据手机号查出的最近的短信详情:{}",smsStreamDo);
        return smsStreamDo == null ? null : smsStreamDo.copyPropertiesTo(new StreamVo());
    }



}
